<?php

namespace app\admin\controller;

use Throwable;
use app\common\controller\Backend;

/**
 * 兑换码使用记录管理
 */
class RedemptionCodeUsage extends Backend
{
    /**
     * RedemptionCodeUsage模型对象
     * @var object
     * @phpstan-var \app\common\model\RedemptionCodeUsage
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'user_id', 'order_id', 'result_id', 'discount_amount', 'original_amount', 'final_amount', 'ip_address', 'user_agent', 'create_time'];

    protected string|array $quickSearchField = ['id','code', 'user.username'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\common\model\RedemptionCodeUsage();
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        
        $res->visible([
            'user' => ['username', 'nickname'],
            'redemption_code' => ['code', 'type', 'batch_name']
        ]);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 统计数据
     */
    public function statistics(): void
    {
        $today = strtotime(date('Y-m-d'));
        $yesterday = $today - 86400;
        $thisMonth = strtotime(date('Y-m-01'));
        $lastMonth = strtotime(date('Y-m-01', strtotime('-1 month')));

        $stats = [
            'today' => $this->model->where('used_at', '>=', $today)->count(),
            'yesterday' => $this->model->where('used_at', '>=', $yesterday)->where('used_at', '<', $today)->count(),
            'this_month' => $this->model->where('used_at', '>=', $thisMonth)->count(),
            'last_month' => $this->model->where('used_at', '>=', $lastMonth)->where('used_at', '<', $thisMonth)->count(),
            'total' => $this->model->count(),
        ];

        // 按类型统计
        $typeStats = $this->model
            ->field('type, count(*) as count')
            ->group('type')
            ->select()
            ->toArray();

        $this->success('', [
            'stats' => $stats,
            'type_stats' => $typeStats,
        ]);
    }

    /**
     * 导出使用记录
     */
    public function export(): void
    {
        $where = [];
        $startTime = $this->request->param('start_time');
        $endTime = $this->request->param('end_time');
        
        if ($startTime) {
            $where[] = ['used_at', '>=', strtotime($startTime)];
        }
        if ($endTime) {
            $where[] = ['used_at', '<=', strtotime($endTime . ' 23:59:59')];
        }

        $records = $this->model
            ->withJoin(['user', 'redemption_code'])
            ->where($where)
            ->order('used_at desc')
            ->select();

        $filename = '兑换码使用记录_' . date('YmdHis') . '.csv';
        header('Content-Type: application/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        
        $output = fopen('php://output', 'w');
        fputcsv($output, ['兑换码', '用户名', '类型', '价值', '使用时间', '批次名称']);
        
        foreach ($records as $record) {
            fputcsv($output, [
                $record->code,
                $record->user->username ?? '',
                $record->type,
                $record->value,
                date('Y-m-d H:i:s', $record->used_at),
                $record->redemption_code->batch_name ?? ''
            ]);
        }
        
        fclose($output);
        exit;
    }

    /**
     * 只读模式，不允许添加、编辑、删除
     */
    public function add(): void
    {
        $this->error(__('Operation not allowed'));
    }

    public function edit(): void
    {
        $this->error(__('Operation not allowed'));
    }

    // public function del(): void
    // {
    //     $this->error(__('Operation not allowed'));
    // }
}